package org.codeart.map.remote;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.codeart.common.response.TerminalResponse;
import org.codeart.common.response.TraceSearchResponse;
import org.codeart.common.util.UrlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 终端服务
 */
@Slf4j
@Service
public class TerminalClient {

    @Value("${system.map.terminal-service-add-api}")
    private String terminalApi;
    
    @Value("${system.map.terminal-around-search-api}")
    private String aroundSearchApi;
    
    @Value("${system.map.trace-terminal-search-api}")
    private String traceSearchApi;

    @Value("${system.map.key}")
    private String key;

    @Value("${system.map.sid}")
    private Integer sid;

    @Autowired
    private RestTemplate restTemplate;

    public TerminalResponse add(String name, String desc) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>() {{
            add("key", key);
            add("sid", sid);
            add("name", name);
            add("desc", desc);
        }};
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
        String json = restTemplate.postForObject(terminalApi, request, String.class);
        JSONObject jsonObject = JSONObject.parseObject(json);
        log.info("高德地图: {}", json);

        Integer tid = jsonObject.getJSONObject("data").getInteger("tid");
        TerminalResponse terminalResponse = new TerminalResponse();
        terminalResponse.setTid(tid);
        return terminalResponse;
    }
    
    public List<TerminalResponse> aroundSearch(String center, Integer radius) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>() {{
            add("key", key);
            add("sid", sid);
            add("center", center);
            add("radius", radius);
        }};
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
        String json = restTemplate.postForObject(aroundSearchApi, request, String.class);
        log.info("高德地图: {}", json);
        
        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONArray results = jsonObject.getJSONObject("data").getJSONArray("results");
        List<TerminalResponse> list = new ArrayList<>();
        for (int i = 0; i < results.size(); i++) {
            TerminalResponse terminalResponse = new TerminalResponse();
            JSONObject obj = results.getJSONObject(i);
            // desc是carId
            Long carId = obj.getLong("desc");
            Integer tid = obj.getInteger("tid");
            
            JSONObject location = obj.getJSONObject("location");
            String longitude = location.getString("longitude");
            String latitude = location.getString("latitude");
            
            terminalResponse.setCarId(carId).setTid(tid).setLongitude(longitude).setLatitude(latitude);
            list.add(terminalResponse);
        }
        
        return list;
    }
    
    public TraceSearchResponse traceSearch(String tid, Long startTime, Long endTime) {
        Map<String, Object> conditions = new HashMap<String, Object>() {{
            put("key", key);
            put("sid", sid);
            put("tid", tid);
            put("starttime", startTime);
            put("endtime", endTime);
        }};

        String url = UrlUtil.createQueryParameters(traceSearchApi, conditions);
        log.info("请求路径: {}", url);
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        log.info("高德地图: {}", response.getBody());

        JSONObject data = JSONObject.parseObject(response.getBody()).getJSONObject("data");
        Integer counts = data.getInteger("counts");
        if (counts == 0) {
            return null;
        }
        JSONArray tracks = data.getJSONArray("tracks");
        long driverMile = 0L;
        long driverTime = 0L;
        for (int i = 0; i < tracks.size(); i++) {
            JSONObject track = tracks.getJSONObject(i);
            Long distance = track.getLong("distance");
            driverMile += distance;
            
            Long time = track.getLong("time");
            time /= 60 * 1000;  // 转为分钟
            driverTime += time;
        }

        TraceSearchResponse traceSearchResponse = new TraceSearchResponse();
        traceSearchResponse.setDriverMile(driverMile).setDriverTime(driverTime);
        return traceSearchResponse;
    }


}
